/*
The MIT License
Copyright (c) 2019 Lehrstuhl Informatik 11 - RWTH Aachen University
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE

This file is part of embeddedRTPS.

Author: i11 - Embedded Software, RWTH Aachen University
*/

#ifndef RTPS_THREADPOOL_H
#define RTPS_THREADPOOL_H

#include "lwip/sys.h"
#include "rtps/communication/PacketInfo.h"
#include "rtps/communication/UdpDriver.h"
#include "rtps/config.h"
#include "rtps/storages/PBufWrapper.h"
#include "rtps/storages/ThreadSafeCircularBuffer.h"


typedef void (*receiveJumppad_fp)(void *callee, const struct rtps_PacketInfo *packet);

struct rtps_Writer;

typedef struct ThreadPool {
	receiveJumppad_fp m_receiveJumppad;
	void *m_callee;
	bool m_running;
	bool bDynamicMem;
	sys_thread_t m_writers[THREAD_POOL_NUM_WRITERS];
	sys_thread_t m_readers[THREAD_POOL_NUM_READERS];
	sys_sem_t m_readerNotificationSem;
	sys_sem_t m_writerNotificationSem;
	struct rtps_ThreadSafeCircularBuffer *m_queueOutgoing;
	struct rtps_ThreadSafeCircularBuffer *m_queueIncoming;
}ThreadPool;
//如果外部为指针。需要申请内存，则入参pPool填NULL.否则将结构体指针传入。
struct ThreadPool *rtps_ThreadPool_Construct(struct ThreadPool *pPool, receiveJumppad_fp receiveCallback, void *callee);
void rtps_ThreadPool_Destruct(struct ThreadPool *pThreadPool);
bool rtps_ThreadPool_addWorkload(struct ThreadPool *pThreadPool, struct rtps_Writer *workload);
void rtps_ThreadPool_readCallback(void *arg, udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, Ip4Port_t port);
void rtps_ThreadPool_deconsturct_packet(void *args);
bool startThreads(struct ThreadPool *pThreadPool);
void stopThreads(struct ThreadPool *pThreadPool);
void clearQueues(struct ThreadPool *pThreadPool);
bool addNewPacket(struct ThreadPool *pThreadPool, struct rtps_PacketInfo *packet);
void writerThreadFunction(void *arg);
void readerThreadFunction(void *arg);
void doWriterWork(struct ThreadPool *pThreadPool);
void doReaderWork(struct ThreadPool *pThreadPool);

#endif // RTPS_THREADPOOL_H
